package com.example.tool.util.sto;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSONObject;
import com.example.tool.util.ExpressDeliveryUtil.ExpressDeliveryResult;
import com.example.tool.util.ExpressDeliveryUtil.ExpressDeliveryTrack;
import com.example.tool.util.ExpressDeliveryUtil.ExpressDeliveryUtil;
import org.apache.commons.lang3.StringEscapeUtils;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import static com.example.tool.util.sto.SignatureUtils.getSignature;

/**
 * 申通快递
 */
public class StoApiUtil {

    // 正式环境地址
    private static final String API_URL = "https://cloudinter-linkgateway.sto.cn/gateway/link.do";
    // 测试环境地址
//     private static final String API_URL = "http://cloudinter-linkgatewaytest.sto.cn/gateway/link.do";
    // 你的应用凭证信息
    private static final String FROM_APP_KEY = "CAKitUhLCDLTpNi";
    private static final String FROM_CODE = "CAKitUhLCDLTpNi";
    private static final String FROM_SECRET_KEY = "XlXGViVGxv2WopZ37DNGSLXo5YnOjr3p";

    /**
     * 查询物流轨迹
     * @param waybillNo
     * @return
     */
    public static  JSONObject queryLogistics(String waybillNo) {
        // 要查询的运单号列表（最多20个）
        List<String> waybillNos = Collections.singletonList(waybillNo);

        // 构建请求参数
        JSONObject content = new JSONObject();
        content.put("order", "asc");
        content.put("waybillNoList", waybillNos);

        // 计算data_digest签名
        String contentStr = content.toString();
        String dataDigest = getSignature(contentStr,FROM_SECRET_KEY);
        // 构建公共参数
        JSONObject params = new JSONObject();
        params.put("api_name", "STO_TRACE_QUERY_COMMON");
        params.put("content", contentStr);
        params.put("from_appkey", FROM_APP_KEY);
        params.put("from_code", FROM_CODE);
        params.put("to_appkey", "sto_trace_query");
        params.put("to_code", "sto_trace_query");
        params.put("data_digest", dataDigest);

        // 发送HTTP请求
        HttpResponse response = HttpRequest.post(API_URL)
                .header("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8")
                .form(params)
                .charset(StandardCharsets.UTF_8)
                .execute();
       return JSONObject.parseObject(StringEscapeUtils.unescapeJava(response.body()));
    }

    /**
     * 订阅物流轨迹信息
     * @param waybillNos 运单号列表
     * @return API响应结果
     */
    public static JSONObject trackSubSubscribe(String waybillNos) {
        JSONObject params = prepareRequestParams(waybillNos);
        // 发送HTTP请求
        HttpResponse response = HttpRequest.post(API_URL)
                .header("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8")
                .form(params)
                .charset(StandardCharsets.UTF_8)
                .execute();
        return JSONObject.parseObject(StringEscapeUtils.unescapeJava(response.body()));
    }

    /**
     * 订阅参数
     */
    private static JSONObject prepareRequestParams(String waybillNos) {
        // 要查询的运单号列表（最多20个）
        List<String> wList = Collections.singletonList(waybillNos);
        // 1. 构建content内容
        List<JSONObject> subscribeInfoList = new ArrayList<>();
        for (int i = 0; i < wList.size(); i++) {
            JSONObject subscribeInfo = new JSONObject();
            subscribeInfo.put("waybillNo", wList.get(i));  // 运单号
            subscribeInfoList.add(subscribeInfo);
        }

        // 构建请求参数
        JSONObject content = new JSONObject();
        content.put("subscribeInfoList", subscribeInfoList);
        // 计算data_digest签名
        String dataDigest = getSignature(content.toString(),FROM_SECRET_KEY);
        // 构建公共参数
        JSONObject params = new JSONObject();
        // 4. 组装最终请求参数
        params.put("api_name", "STO_TRACE_PLATFORM_SUBSCRIBE");
        params.put("content", content);
        params.put("from_appkey", FROM_APP_KEY);
        params.put("from_code", FROM_CODE);
        params.put("to_appkey", "sto_trace_platform");
        params.put("to_code", "sto_trace_platform");
        params.put("data_digest", dataDigest);
        return params;
    }
    // 正式环境地址
    private static final String PROD_URL = "https://cloudinter-linkgateway.sto.cn/gateway/link.do";
    /**
     * 查询售后工单
     * @return 查询结果
     */
    public static JSONObject queryAfterSale(String billCodes) {
        // 1. 准备请求URL
        String url = "https://cloudinter-linkgateway.sto.cn/gateway/link.do";

        // 2. 构建content参数
        JSONObject content = new JSONObject();
        content.put("billCodes", Collections.singletonList(billCodes));
        content.put("demandTicketTypeCode", 0);
        content.put("gmtCreateStart", System.currentTimeMillis() - 7 * 24 * 60 * 60 * 1000);
        content.put("gmtCreateEnd", System.currentTimeMillis());
        content.put("pageNum", 1L);
        content.put("pageSize", 100L);
        content.put("statusCode", "0");
        // 可选参数
        content.put("shopKey", "FE74B393757881089702FC691B049011");

        // 3. 构建公共参数
        MultiValueMap<String, Object> paramsMap = new LinkedMultiValueMap<>();
        paramsMap.add("api_name", "CHAOSHANG_AFTERSALE_QUERY");
        paramsMap.add("from_appkey", FROM_APP_KEY); // 替换为你的appkey
        paramsMap.add("from_code", FROM_CODE);   // 替换为你的from_code
        paramsMap.add("to_appkey", "sto_merchant");
        paramsMap.add("to_code", "sto_merchant");
        paramsMap.add("content", content.toString());

        // 4. 生成签名 (appSecret需要替换为你的实际密钥)
        String dataDigest = getSignature(content.toString(), FROM_SECRET_KEY);
        paramsMap.add("data_digest", dataDigest);

        // 5. 发送请求
        RestTemplate restTemplate = new RestTemplate();
        try {
            restTemplate.getMessageConverters().set(1,
                    new StringHttpMessageConverter(StandardCharsets.UTF_8));
            String response = restTemplate.postForObject(url, paramsMap, String.class);
            System.out.println("接口响应: " + response);
            return JSONObject.parseObject(response);
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("请求失败: " + e.getMessage());
        }
        return null;
    }



    public static void main(String[] args) {
        ExpressDeliveryResult result = ExpressDeliveryUtil.queryLogistics("1347825587430");
        List<ExpressDeliveryTrack> tracks = result.getTracks();
//        boolean b = tracks.stream().filter(e -> e.getIsTransfer() && ObjectUtil.equal(e.getScanType(), RECEIVED.getCode())).count() == 0;
//        boolean b = tracks.stream().noneMatch(e -> e.getIsTransfer() && ObjectUtil.equal(e.getScanType(), RECEIVED.getCode()));
//        System.out.println(b);
        for (ExpressDeliveryTrack t: tracks){
            System.out.println(t.toString());
        }
//        System.out.println( ExpressDeliveryUtil.queryLogistics("777322470176556"));
    }
   /* public static void main(String[] args) {
        // 要查询的运单号列表（最多20个）
        List<String> waybillNos = Arrays.asList("777031922725111");

        // 构建请求参数
        JSONObject content = new JSONObject();
        content.set("order", "asc");
        content.set("waybillNoList", waybillNos);

        // 计算data_digest签名
        String contentStr = content.toString();
        String dataDigest = DigestUtil.md5Hex(contentStr + "your_secret_key"); // 替换为你的密钥

        // 构建公共参数
        JSONObject params = new JSONObject();
        params.set("api_name", "STO_TRACE_QUERY_COMMON");
        params.set("content", contentStr);
        params.set("from_appkey", FROM_APP_KEY);
        params.set("from_code", FROM_CODE);
        params.set("to_appkey", TO_APP_KEY);
        params.set("to_code", TO_CODE);
        params.set("data_digest", dataDigest);

        // 发送HTTP请求
        HttpResponse response = HttpRequest.post(API_URL)
                .header("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8")
                .form(params)
                .execute();

        // 输出响应结果
        if (response.isOk()) {
            System.out.println("查询结果：" + response.body());
        } else {
            System.out.println("请求失败，状态码：" + response.getStatus());
            System.out.println("错误信息：" + response.body());
        }
    }*/
}
